import {errorConfig} from './requestErrorConfig';
import {user} from '@/services/Auth';
import {history} from 'umi';

/* array to tree */
const arrayToTree = (arr, parent = 0) =>
  arr.filter(item => item.pid === parent)
    .map(child => ({
      ...child, routes: arrayToTree(arr,
        child.id),
    }));


export async function getInitialState() {

  if (history.location.pathname !== '/login') {
    let initialState = {loginInfo: {}, routes: [], access: []};
    let resp = await user();

    if (0 === resp.code) {
      // 侧边栏菜单
      let routes = arrayToTree(
        (resp.data?.menuList ?? [])
          .filter(d => d.menuType === 'M')
          .map(d => {
            d.name = d.menuName;
            d.hideInMenu = d.visible !== 1;
            return d;
          }),
      );
      // 完整侧边栏
      routes = [
        {path: '/', component: '@/pages/index/App', icon: 'icon-shouye', name: '首页管理'},
        {path: '/login', component: '@/pages/login/App', layout: false},
        ...routes,
        {path: '/*', component: '@/pages/404.js'},
      ];

      // 访问权限
      let access = (resp.data?.menuList ?? [])
        .filter(d => d.permission !== '' && d.permission !== null)
        .map(d => d.permission.replaceAll(':', '_'));

      let accessObj = {};
      access.forEach(d => {
        accessObj[d] = true;
      });

      initialState.loginInfo = resp.data;
      initialState.routes = routes;
      initialState.access = accessObj;
    }

    return initialState;
  }
}

export const request = {
  ...errorConfig,
};
